<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
// use App\Models\Site;
use App\Models\PriDeviceInfo;
use DB;

class GenerateWateraff extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:wateraff {date?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'generate water aff data';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::transaction(function () {
           // DB::statement('truncate table t_realdata_wateraff;');
           // $this->saveData();
        });
    }
    
    //获取水厂信息
    protected function getSitesInfo() {
        $info = PriDeviceInfo::select(['AreaId', 'pdi_index'])
                ->with(['area'=>function($query){
                    $query->select(['id', 'name']);
                }])
                ->get()
                ->toArray();
        return $info;
    }
    
    //保存信息
    protected function saveData() {
        $date = $this->argument('date');
        if(!$date) {
            $inputDate = time();
        }else{
            $inputDate = strtotime($date);
        }
        $range=config('water.waterRange');
        $info = $this->getSitesInfo();
        $data=[];
        $prefix="rd_";
        $history=[];
        $hPrefix="hd_";
        foreach ($info as $k=>$v) {
            $pdi = array_get($v, 'pdi_index');
            $name = array_get($v, 'area.name');
            $config= array_get($range, $name);
            $temp = [
                'pdi_index'=>$pdi,
                'rd_updatetime'=>date('Y-m-d H:i:s', $inputDate),
            ];
            $htemp=[
                'pdi_index'=>$pdi,
                'rd_updatetime'=>date('Y-m-d H:i:s', $inputDate),
                'hd_datetime'=> date('Y-m-d H:i:s', strtotime('+10 seconds', $inputDate)),
            ];
            foreach ($config as $kk => $vv) {
                $temp[$prefix.$kk] = randomFloat(...$vv);
                $htemp[$hPrefix.$kk] = randomFloat(...$vv);
            }
            $temp[$prefix."AllFlow"] = $temp[$prefix."Flow"] * 24;
            $htemp[$hPrefix."AllFlow"] = $htemp[$hPrefix."Flow"] * 24;
            $data[] = $temp;
            $history[] = $htemp;
        }
        DB::table('t_realdata_wateraff')->insert($data);
        DB::table('t_hisdata_wateraff')->insert($history);
    }
}
